import json
import re

import pandas as pd


# file_sorted用于对excel文件按照by=['内容分类', '实体事件']的顺序进行单元格排序，方便后续加库
def file_sorted(input_filename):
    stexcel = pd.read_excel(input_filename)
    stexcel.sort_values(by=['内容分类', '实体事件'], inplace=True, ascending=[True, True])
    # print(stexcel)
    stexcel.to_excel(input_filename, encoding="utf-8")


# 将文字转换成json格式的数据
def word_to_ascii(input_filename):
    # f = open(doc_dict_dir + 'demo.json', 'rb')
    f = open(input_filename, 'rb')
    # 使用load的方法将数据从pkl文件中读取出来
    info = json.load(f)
    # res_f = open('../Test/test.pkl', 'w+')
    res_f = open(input_filename, 'w+')
    json.dump(info, res_f, indent=4, separators=(',', ':'), ensure_ascii=True)
    # 关闭文件
    f.close()


# 匹配关键词name和输入data的句子
def is_matched(key_word, match_party):
    # start = time.time()
    flag = False
    # match = None
    # 完全匹配key_word的情况
    if re.search(key_word, match_party):
        flag = True
        # match = key_word
        # return flag, match, time.time() - start
        return flag
    # 不能完全匹配key_word，有容错的情况
    else:
        del_num = int(len(key_word) / 2.1)  # 容错or删掉的字符个数
        for idx in range(len(key_word) - del_num + 1):
            re_key_word = key_word[:idx] + '.*' + key_word[idx + del_num:]  # 正则化查找的字符串
            # print(re_key_word)
            match = re.search(re_key_word, match_party)
            if match is not None:
                flag = True
                # match = match.group()
                # return flag, match, time.time() - start
                return flag
    return flag
